package mspbots.teams.data.core.users;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.teams.common.ResultMsg;
import mspbots.teams.data.core.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ManagerReceiver extends BaseReceiver {

    private final ManagerRepository managerRepository;

    @RabbitListener(queues = "data-teams.manager.sync")
    public void processCompanies(ResultMsg resultMsg) {

        Manager data = Manager.builder().otherId(resultMsg.getId()).build();
        data.setExtend(resultMsg.getEntity());
        data.setTenantId(resultMsg.getTenantId());
        data.setSyncTime(resultMsg.getSyncDate());
        data.setCreateTime(LocalDateTime.now());
        data.setUpdateTime(LocalDateTime.now());

        this.managerRepository.findByOtherIdAndTenantId(data.getOtherId(), data.getTenantId())
                .switchIfEmpty(this.managerRepository.save(data))
                .filter(old->old.getUpdateTime().isBefore(data.getUpdateTime()))
                .map(old -> {
                    data.setId(old.getId());
                    return data;
                })
                .flatMap(this.managerRepository::save).block(Duration.ofSeconds(10));
    }
}
